/*
 * @Author: szx
 * @Date: 2022-07-04 12:59:13
 * @LastEditTime: 2022-07-04 13:39:36
 * @Description:
 * @FilePath: \leetcode\500-599\556\556.js
 */
/**
 * @param {number} n
 * @return {number}
 */
var nextGreaterElement = function (n) {
    const nums = [];
    while (n >= 1) {
        nums.push(n % 10);
        n = Math.floor(n / 10);
    }
    nums.reverse();
    //从后往前遍历找到相邻升序的数字
    let i = nums.length - 2;
    while (i >= 0 && nums[i] >= nums[i + 1]) i--;
    //从i到末尾找到比i大的数字交换
    let j = nums.length - 1;
    if (i >= 0) {
        while (nums[j] <= nums[i]) j--;
        [nums[i], nums[j]] = [nums[j], nums[i]];
    } else return -1;
    i++;
    j = nums.length - 1;
    // 然后reserve，i+1到末尾
    while (i < j) {
        [nums[i], nums[j]] = [nums[j], nums[i]];
        i++;
        j--;
    }
    return Number.parseInt(nums.join(''));
};
